const { exec } = require('child_process')

const encapsulation = (path, desc = '应用') => {
  // 启动应用
  const AppProcess = exec(path, (error, stdout, stderr) => {
    if (error) {
      console.error('\n\n\n')
      console.error(`${desc}进程出错:`, error)
    }
    if (stdout) {
      console.log('\n\n\n')
      console.log(`${desc}进程输出:`, stdout)
    }
    if (stderr) {
      console.error('\n\n\n')
      console.error(`${desc}进程错误输出::`, stderr)
    }
  })

  AppProcess.stdout.pipe(process.stdout)
  AppProcess.stderr.pipe(process.stderr)

  return AppProcess
}

const baseAppProcess = encapsulation('npm run serve  --prefix ./vuefront/.')
const subAppProcess = encapsulation('npm run dev --prefix ./secondaryreact/.')
const nodeBffProcess = encapsulation('npm run dev --prefix ./nodeBFF/.')

// 监听进程关闭事件
process.on('SIGINT', () => {
  // 关闭基座应用进程
  baseAppProcess.kill('SIGTERM')

  // 关闭子应用进程
  subAppProcess.kill('SIGTERM')

  // 关闭子 node BFF 进程
  nodeBffProcess.kill('SIGTERM')
})
